package scheduledtasks.hander;


import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import scheduledtasks.entity.TaskObj;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class SqlHander {
    @Autowired
    private SqlSession sqlSession;
    public List<TaskObj> connection(String sql){
        ResultSet rs=null;
        String str=null;
        Connection connections=null;
        List<TaskObj> list=new ArrayList<>();
        try {
            connections=sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
            Statement s=connections.createStatement();
            rs= s.executeQuery(sql);

            while (rs.next()){
                TaskObj taskObj = new TaskObj();
                taskObj.setId(rs.getInt("id"));
                taskObj.setMethoName(rs.getString("metho_name"));
                taskObj.setClassName(rs.getString("class_name"));
                taskObj.setCron(rs.getString("cron"));
                taskObj.setTime(System.currentTimeMillis());
                taskObj.setSync(0);
                list.add(taskObj);
            }
            connections.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return  list;
    }


    public String uodate(String sql){
        ResultSet rs=null;
        String str=null;
        Connection connections=null;
        try {
            connections=sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
            Statement s=connections.createStatement();
             s.execute(sql);
            connections.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return "";
    }


    public boolean connectionisHave(String sql){
        ResultSet rs=null;
        String str=null;

        Connection connections=null;
        try {
            connections=sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
            Statement s=connections.createStatement();
            rs= s.executeQuery(sql);
            while (rs.next()){
                str=rs.getString("class_name");
            }
            connections.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        if(null==str){
            return false;
        }
        return  true;

    }










    private void ex(String sql){
        Connection connections=null;
        try {
            connections=sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
            Statement s=connections.createStatement();

            s.execute(sql);
            connections.close();
        }catch (SQLException e){

        }
    }
}
